package com.xyht.medicine_management_system.auth.aop;

import com.xyht.medicine_management_system.auth.util.JwtTokenUtil;
import com.xyht.medicine_management_system.common.commonReturn.CommonCodeEnum;
import com.xyht.medicine_management_system.common.commonReturn.CommonResult;
import com.xyht.medicine_management_system.common.commonReturn.ExceptionCast;
import com.xyht.medicine_management_system.common.commonReturn.ResponseResult;
import com.xyht.medicine_management_system.modules.user.entity.MmsUser;
import com.xyht.medicine_management_system.modules.user.mapper.MmsUserMapper;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.xyht.medicine_management_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.medicine_management_system.modules.user.constant.QualificationTypeConstant.QUALIFICATION_TYPE_NONE;

@Aspect
@Component
@Log4j2
@Order(1)
public class MedicineAop {
    @Resource
    private HttpServletRequest request;
    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Resource
    private MmsUserMapper userMapper;

    public MedicineAop(HttpServletRequest request) {
        this.request = request;
    }

    @Pointcut("@annotation(com.xyht.medicine_management_system.auth.annotation.MedicineAnnotation)")
    private void medicinePointcut(){
    }

    /**
     * 校验用户是否有资质
     */
    @Before("medicinePointcut()")
    public void permissionCheckMedicine(){
        String userId = jwtTokenUtil.getUserIdOrNullByRequest(request);
        if (!isNullOrEmpty(userId)) {
            MmsUser user = userMapper.selectById(userId);
            Integer qualificationType = user.getQualificationType();

            if (qualificationType == QUALIFICATION_TYPE_NONE) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.MEDICINE_NOT_AUTH));
            }
        }

    }


}
